﻿using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;

namespace ZH.GPT.Extend
{
    /// <summary>
    /// 配置文件的扩展
    /// 注意：配置文件中比如ConnectionStrings:SlaveConnectionList这个节点，在环境变量中会配置成ConnectionStrings_SlaveConnectionList
    /// </summary>
    public static class IConfigurationExtend
    {
        /// <summary>
        /// 更换环境变量值
        /// </summary>
        /// <param name="configuration"></param>
        /// <param name="configKey"></param>
        /// <param name="environmentKey"></param>
        public static string SetConfigurationByEnvironment(this IConfiguration configuration, string configKey, string environmentKey)
        {
            var connectionString = configuration[configKey];
            if (!string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(environmentKey)))
            {
                connectionString = Environment.GetEnvironmentVariable(environmentKey);
                configuration[configKey] = connectionString;
            }
            return connectionString;
        }

        /// <summary>
        /// 更换环境变量值
        /// </summary>
        /// <param name="configuration"></param>
        /// <param name="configKey"></param>
        /// <param name="environmentKey"></param>
        /// <returns></returns>
        public static List<string> SetConfigurationsByEnvironment(this IConfiguration configuration, string configKey, string environmentKey)
        {
            List<string> list = (List<string>)configuration.GetSection(configKey).Get(typeof(List<string>));
            if (!string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(environmentKey)))
            {
                string connectionString = Environment.GetEnvironmentVariable(environmentKey);
                list = new List<string>(connectionString.Split('|'));
                for (int i = 0; i < list.Count; i++)
                {
                    string value = list[i];
                    configuration[$"ConnectionStrings:SlaveConnectionList:{i}"] = value;
                }
            }
            return list;
        }
    }
}
